/**
 * @ClassName: SysProductUtils
 * @author linsen
 * @date 2016-10-11
 */
package com.fzrskj.cloud.free.sys.utils;

import com.fzrskj.cloud.free.consts.AppCode;
import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.bean.DicParam;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.bean.DomainParam;
import com.fzrskj.cloud.free.sys.bean.SysProduct;
import com.fzrskj.cloud.free.sys.bean.SysProductView;
import com.fzrskj.cloud.free.sys.dao.SysProductDao;
import ms.core.object.CObject;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;

import java.util.*;

public class SysProductUtils extends CObject {

    public List<SysProductView> getProductList(Integer status, String productClass, String subClass, String productCode, Integer recommend, String productName, int page, int pagesize) {
        Map<String, Object> cdt = new HashMap<String, Object>();
        cdt.put("status", status);
        cdt.put("productClass", productClass);
        if (!StrTool.isBlankStr(subClass)) {
            cdt.put("subClass", subClass);
        }
        if (!StrTool.isBlankStr(productCode)) {
            cdt.put("productCode", productCode);
        }
        if (recommend > -1) {
            cdt.put("recommend", recommend);
        }
        if (!StrTool.isBlankStr(productName)) {
            cdt.put("productName", productName);
        }
        SysProductDao dao = new SysProductDao();
        List<SysProductView> list = dao.getProductList(cdt, page, pagesize);
        String code = dao.getErrCode();
        this.setErrCode(code);
        dao.dispose();
        return list;
    }


    //获取产品列表
    public List<SysProductView> getProductList(Integer status, String productClass, Integer recommend, int page, int pagesize) {
        Map<String, Object> cdt = new HashMap<String, Object>();
        cdt.put("status", status);
        cdt.put("productClass", productClass);
        if (recommend > -1) {
            cdt.put("recommend", recommend);
        }
        SysProductDao dao = new SysProductDao();
        List<SysProductView> list = dao.getProductList(cdt, page, pagesize);
        String code = dao.getErrCode();
        this.setErrCode(code);
        dao.dispose();
        return list;
    }

    public List<SysProductView> getProductList(String productClass, String regType, int page, int pagesize, Map<String, Object> filter) {
        return this.getProductList(productClass, regType, page, pagesize, filter, null);
    }

    /**
     * 获取产品列表.
     *
     * @param productClass 分类.
     * @param regType      注册商.
     * @param page         page from.
     * @param pagesize     page size.
     * @return product list.
     */
    public List<SysProductView> getProductList(String productClass, String regType, int page, int pagesize, Map<String, Object> filter, String subClass) {
        Map<String, Object> cdt = new HashMap<String, Object>();
        cdt.put("productClass", productClass);
        if (!StrTool.isBlankStr(regType)) {
            cdt.put("regType", regType);
        }
        if (!StrTool.isBlankStr(subClass)) {
            cdt.put("subClass", subClass);
        }
        SysProductDao dao = new SysProductDao();
        List<SysProductView> list = dao.getProductList(cdt, page, pagesize, filter);
        String code = dao.getErrCode();
        this.setErrCode(code);
        dao.dispose();
        return list;
    }
    public int getProductRows(Map<String, Object> cdt) {
        return this.getProductRows(cdt, new HashMap<>());
    }

    //获取产品总数
    public int getProductRows(Map<String, Object> cdt, Map<String, Object> filter) {
        SysProductDao dao = new SysProductDao();
        int rows = dao.querySysProductCount(cdt, filter);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return rows;
    }

    //添加产品
    public int addSysProduct(SysProduct sysproduct) {
        Map<String, Object> cdt = new HashMap<>();
        cdt.put("productCode", sysproduct.getProductCode());
        cdt.put("productClass", sysproduct.getProductClass());

        SysProductDao dao = new SysProductDao();
        int count = dao.querySysProductCount(cdt);
        if (count > 0) {
            dao.dispose();
            this.setErrCode(AppCode.PRODUCT_ALREADY_EXISTS);
            return 0;
        }
        sysproduct.setCreateTime(new Date());
        sysproduct.setListId(0);
        sysproduct.setSaleType(0);
        sysproduct.setStatus("2");
        sysproduct.setUserGradeSale(2);
        int ret = dao.addSysProduct(sysproduct);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return ret;
    }

    //修改产品信息
    public int modSysProduct(Map<String, Object> values, Map<String, Object> cdt) {
        SysProductDao dao = new SysProductDao();
        int i = dao.modSysProduct(values, cdt);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return i;
    }

    //删除产品(根据产品编号)
    public int delSysProduct(Map<String, Object> cdt) {
        SysProductDao dao = new SysProductDao();
        int i = dao.delSysProduct(cdt);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return i;
    }

    //查询产品
    public SysProductView querySysProduct(Map<String, Object> cdt) {
        SysProductDao dao = new SysProductDao();
        SysProductView view = dao.querySysProduct(cdt);

        //虚拟主机产品合并主平台参数到产品配置中
        if (null != view && CloudContextUtils.getAgentId() > 0 && (ProductTypeEnum.V_HOST.equals(view.getProductClass()) || ProductTypeEnum.DIY.equals(view.getProductClass()))) {
            Map<String, Object> cdtBase = new HashedMap();
            cdtBase.put("productClass", view.getProductClass());
            cdtBase.put("productCode", view.getProductCode());
            cdtBase.put("sp.regType", view.getRegType());
            cdtBase.put("sp.agentId", CloudContextUtils.DEF_AGENT_ID);
            SysProductView viewPlat = dao.querySysProduct(cdtBase);
            if (!StrTool.isBlankStr(viewPlat.getProductParam())) {
                JSONObject paramPlat = JSONObject.fromObject(viewPlat.getProductParam());
                JSONObject param = JSONObject.fromObject(view.getProductParam());
                paramPlat.putAll(param);
                view.setProductParam(paramPlat.toString());
            }
        }

        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return view;
    }

    public SysProductView querySysProduct(String productClass, String productCode) {
        Map<String, Object> cdt = new HashedMap();
        cdt.put("productClass", productClass);
        cdt.put("productCode", productCode);
        return this.querySysProduct(cdt);
    }

    public SysProductView querySysProductAppointAgent(String productClass, String productCode, Integer agentId) {
        Map<String, Object> cdt = new HashedMap();
        cdt.put("productClass", productClass);
        cdt.put("productCode", productCode);
        cdt.put("sp.agentId", agentId);
        return this.querySysProduct(cdt);
    }

    public SysProductView querySysProductAppointAgent(String productClass, String productCode, String retType, Integer agentId) {
        Map<String, Object> cdt = new HashedMap();
        cdt.put("productClass", productClass);
        cdt.put("productCode", productCode);
        cdt.put("sp.regType", retType);
        cdt.put("sp.agentId", agentId);
        return this.querySysProduct(cdt);
    }

    /**
     * 通用产品配置.
     *
     * @param product
     * @param priceItem
     * @param typeEnum
     * @return
     */
    public int saveProductSet(JSONObject product, JSONArray priceItem, ProductTypeEnum typeEnum) {
        Map<String, Object> map = new HashMap<>();
        map.put("productName", product.getString("productName"));
        map.put("productDetail", product.getString("productDetail"));
        map.put("productParam", product.toString());
        map.put("status", product.getString("status"));
        map.put("remark", product.getString("productDetail"));
        map.put("regType", typeEnum.getTag());

        //更新条件
        Map<String, Object> mapCod = new HashMap<>();
        mapCod.put("productCode", product.getString("productCode"));
        SysProductDao dao = new SysProductDao();
        int i = dao.modSysProduct(map, mapCod);
        this.setErrCode(dao.getErrCode());
        dao.dispose();

        //价格设置方式 1 - 会员折扣  2 - 按会员等级设置
        int saleType = null != product && product.containsKey("saleType") ? StrTool.strToIntDef(product.getString("saleType"), 1) : 1;

        if (i > 0 && !priceItem.isEmpty()) {
            if (typeEnum.equals(ProductTypeEnum.DIY) && saleType == 2) {
                mapCod.put("productClass", typeEnum.getTag());
                SysDiyProductPriceUtils sysDiyProductPriceUtils = new SysDiyProductPriceUtils();
                sysDiyProductPriceUtils.delSysDiyProductPrice(mapCod);
                sysDiyProductPriceUtils.addSysDiyProductPrice(priceItem.toString(), typeEnum.getTag());
                sysDiyProductPriceUtils.dispose();
            } else {
                //更新购买时长
                SysPromotionUtils sysPromotionUtils = new SysPromotionUtils();
                sysPromotionUtils.delSysPromotion(mapCod);
                sysPromotionUtils.addSysPromotion(priceItem.toString());
            }
        }

        //强制更新代理产品说明
        SysProductAgentHelper.mustUpdateProductDetail(typeEnum, product.getString("productCode"));

        return i;
    }

    //删除域名价格(按注册商配置的价格)
    public int delDomainProductSetPriceByRegType(String productClass, String productCode) {
        //更新产品价格
        SysProductPriceUtils utils = new SysProductPriceUtils();
        int i = utils.delSysDomainProductPriceNotDefaule(productClass, productCode);
        this.setErrCode(utils.getErrCode());
        return i;
    }

    //获取产品默认价格
    public List<SysProductView> getProDefaultPrice(Map<String, Object> cdt) {
        DicParamUtils dpUtils = new DicParamUtils();
        String showPriceLevel = dpUtils.getParamValue("showPriceLevel", 1);
        SysProductDao dao = new SysProductDao();
        List<SysProductView> list = dao.getProDefaultPrice(cdt, showPriceLevel);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return list;
    }

    /**
     * 根据字段查询集合
     *
     * @param productClass
     * @return
     */
    public List<SysProduct> queryProductClass(String productClass) {
        SysProductDao dao = new SysProductDao();
        List<SysProduct> list = dao.queryProductClass(productClass);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return list;
    }

    /**
     * 根据实例Id查询产品
     *
     * @param productCode
     * @return
     */
    public SysProduct queryProductByProductCode(String productCode) {
        SysProductDao dao = new SysProductDao();
        SysProduct sp = dao.queryProductByProductCode(productCode);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return sp;
    }

    public SysProduct getProductAppointAgent(String productClass, String productCode, Integer agentId) {
        SysProductDao dao = new SysProductDao();
        SysProduct sp = dao.getProductAppointAgent(productClass, productCode, agentId);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
        return sp;
    }

    /**
     * 代理同步慧林虚机产品
     *
     * @return
     */
    public void syncAgentWiniisVHostProduct() {
        syncAgentProduct(ProductTypeEnum.V_HOST.getTag());
    }

    /**
     * 代理同步自定义产品
     *
     * @return
     */
    public void syncAgentDiyProduct() {
        syncAgentProduct(ProductTypeEnum.DIY.getTag());
    }

    /**
     * 代理同步域名产品
     *
     * @return
     */
    public void syncAgentDomainProduct() {
        syncAgentProduct(ProductTypeEnum.DOMAIN.getTag());
    }

    /**
     * 同步产品描述和状态.
     *
     * @param agentId 代理ID.
     */
    public void syncAgentProductDetailAndStatus(Integer agentId) {
        SysProductDao dao = new SysProductDao();
        dao.syncAgentProductDetailAndStatus(agentId);
        this.setErrCode(dao.getErrCode());
        dao.dispose();
    }

    public void syncAgentProduct(String productClass) {
        syncAgentProduct(productClass, CloudContextUtils.getAgentId());
    }

    /**
     * 代理域名产品同步
     *
     * @return
     */
    public void syncAgentProduct(String productClass, Integer targetAGentId) {
        SysProductDao dao = new SysProductDao();
        Map<String, Object> cdt = new HashMap<>();
        List<SysProduct> sysProductList = dao.queryAgengtSysProduct(productClass, productClass, 0);
        List<SysProduct> agentProductList = dao.queryAgengtSysProduct(productClass, productClass, targetAGentId);

        System.out.println("sysProductList size = " + sysProductList.size());
        System.out.println("agentProductList size = " + agentProductList.size());

        List<SysProduct> addProductList = getDifferenceProductList(sysProductList, agentProductList);
        List<SysProduct> delProductList = getDifferenceProductList(agentProductList, sysProductList);

        DicParamUtils paramUtils = new DicParamUtils();
        Double premium = Double.valueOf(20);
        DicParam dicParam = paramUtils.getParamByNameAndType(DicParamEnum.DIY_PRICE_PREMIUM.getVal(), 1);
        if (null != dicParam) {
            premium = Double.valueOf(dicParam.getParamValue());
        }

        //删除产品
        for (SysProduct p : delProductList) {
            cdt.clear();
            cdt.put("agentId", targetAGentId);
            cdt.put("id", p.getId());
            dao.delAgentSysProduct(cdt);
        }

        //添加产品
        for (SysProduct p : addProductList) {
            //没有完整配置的产品不更新
            Boolean isNotSetProduct = false;
            //不正常的产品不同步
            if (!p.getStatus().equals("1")) {
                continue;
            }

            if(CStrTool.isBlankStr(p.getProductParam())){
                isNotSetProduct = true;
            }

            p.setAgentId(targetAGentId);
            if (!productClass.equals(ProductTypeEnum.DOMAIN.getTag())) {
                p.setProductParam("");
            }


            com.alibaba.fastjson.JSONObject productParam = new com.alibaba.fastjson.JSONObject();
            if (productClass.equals(ProductTypeEnum.V_HOST.getTag()) || productClass.equals(ProductTypeEnum.DIY.getTag())) {
                //不同步的虚机产品
                if (isNotSetProduct && productClass.equals(ProductTypeEnum.V_HOST.getTag())) {
                    continue;
                }
                productParam.clear();
                productParam.put("productCode", p.getProductCode());
                productParam.put("productName", p.getProductName());
                productParam.put("productDetail", p.getProductDetail());
                productParam.put("status", 1);
                productParam.put("premium", premium);
                p.setProductParam(productParam.toJSONString());
            }
            dao.addAgentSysProduct(p);
        }

        this.setErrCode(dao.getErrCode());
        dao.dispose();
    }

    /**
     * 取出差异产品
     *
     * @param productList1
     * @return
     */
    private List<SysProduct> getDifferenceProductList(List<SysProduct> productList1, List<SysProduct> productList2) {
        List<SysProduct> differenceProductList = new ArrayList<>();
        do {
            if (productList2.size() == 0) {
                differenceProductList = productList1;
                break;
            }
            Boolean isExist = false;
            for (SysProduct p1 : productList1) {
                isExist = false;
                String p1ProductCode = p1.getProductCode();
                String p1ProductClass = p1.getProductClass();
                String p1SubClass = p1.getSubClass();
                for (SysProduct p2 : productList2) {
                    String p2ProductCode = p2.getProductCode();
                    String p2ProductClass = p2.getProductClass();
                    String p2SubClass = p2.getSubClass();
                    if (p1ProductCode.equals(p2ProductCode) && p1ProductClass.equals(p2ProductClass)) {
                        if (!StrTool.isBlankStr(p1SubClass) && !StrTool.isBlankStr(p2SubClass)) {
                            if (p2SubClass.equals(p1SubClass)) {
                                isExist = true;
                            }
                        }else{
                            isExist = true;
                        }
                    }
                }

                if (!isExist) {
                    differenceProductList.add(p1);
                }
            }
        } while (false);
        return differenceProductList;
    }
}
